import React, { ReactElement, useContext } from 'react';
import { View, ScrollView, Text } from 'react-native';
import { groupWith, map, pipe } from 'ramda';
import moment from 'moment';

import styles from './style';
import { Store } from '../../reducer';
import Empty from '../../../../components/Empty';
import Lesson from '../Lesson';
import { LessonInfo } from '../../../../api/class/getLessons';

interface LessonData {
  key: string;
  lessonList: LessonInfo[];
  index: number;
}

const WEEK = ['日', '一', '二', '三', '四', '五', '六'];

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { lesson } = state;
  const { lessons = [] } = lesson;

  const list = pipe(
    groupWith(
      (left: LessonInfo, right: LessonInfo): boolean =>
        moment(left.lessonStartTime).format('YYYY-MM-DD') ===
        moment(right.lessonStartTime).format('YYYY-MM-DD')
    ),
    (lessonData: LessonInfo[][]): LessonData[] =>
      lessonData.map(
        (lessonList, index): LessonData => ({
          key:
            lessonList[0].lessonStartTime !== ''
              ? `${moment(lessonList[0].lessonStartTime).format(
                  'YYYY-MM-DD'
                )} 星期${WEEK[moment(lessonList[0].lessonStartTime).day()]}`
              : '敬请期待',
          lessonList,
          index
        })
      )
  )(lessons);

  return (
    <View style={styles.container}>
      {lessons.length > 0 ? (
        <ScrollView
          contentContainerStyle={styles.list}
          showsVerticalScrollIndicator={false}
        >
          {list.map(
            ({ key, lessonList, index }): ReactElement => (
              <View style={styles.lessonContent} key={`${key}-${index}`}>
                <View style={styles.descContent}>
                  <View style={styles.line} />
                  <Text style={styles.desc}>{key}</Text>
                </View>
                {lessonList.map(
                  (item, i): ReactElement => {
                    return (
                      // eslint-disable-next-line react/no-array-index-key
                      <Lesson key={`${item.lessonResourceId}-${i}`} {...item} />
                    );
                  }
                )}
              </View>
            )
          )}
        </ScrollView>
      ) : (
        <Empty emptyDesc="暂无课程" />
      )}
    </View>
  );
};
